<template>
  <div class="upload-image">
    <img class="image-view" :src="imgUrl || uploadDefault"/>
    <el-upload
      :headers="importHeaders"
      :action="action"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <el-button type="primary" size="small">上传图片</el-button>
    </el-upload>
  </div>
</template>

<script>
import uploadDefault from '@/assets/upload-default.png'
import { getToken } from '@/utils/auth'

export default {
  name: 'UploadImage',
  props: ['value', 'pathPrefix', 'uploadUrl', 'method'],
  data() {
    this.importHeaders = {
      token: getToken()
    }
    return {
      uploadDefault,
      imgUrl: this.value
    }
  },
  computed: {
    action() {
      return this.uploadUrl ? process.env.VUE_APP_BASE_API +  this.uploadUrl : `${process.env.VUE_APP_BASE_API}/platform/file/upload/images/${this.pathPrefix || ''}`
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.imgUrl = res.data.url
        this.$emit('input', `${res.data.key}`);
      }
    },
    beforeAvatarUpload() {
      return true;
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-image{
  overflow: hidden;

  .image-view{
    float: left;
    margin-right: 20px;
    width: 120px;
    height: 120px;
  }
}
</style>